﻿using DataManageSystem.Common;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WebController : ControllerBase
    {
        private readonly UserServices userService;

        public WebController(UserServices userService)
        {
            this.userService = userService;
        }

        [HttpPost("login")]
        public ObjectResult login([FromBody] User user)
        {
            if (string.IsNullOrEmpty(user.Username) || string.IsNullOrEmpty(user.Password))
            {
                return new ObjectResult("数据输入不合法");
            }

            try
            {
                User? u = userService.login(user);
                return new ObjectResult(Result.Success(u));
            }
            catch (ServiceException e)
            {
                return new ObjectResult(Result.Error(e.Message));
            }
            catch (Exception e)
            {
                return new ObjectResult(Result.Error());
            }
        }
    }
}
